package com.baidu.ota.impl;

import android.content.Context;
import android.os.PowerManager;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 大于Android 6.0(API=23)的版本
 */
public class RecoverySystemGT23 extends RecoverySystem {
    @Override
    public String installSystemOnNextBoot(Context context, File file) {
        try {
            processPackage(context, file);
            installPackageNextBoot(context, file);
        } catch (Exception e) {
            return e.toString();
        }
        return "";
    }

    @Override
    public void reboot2Recovery(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm != null) {
            pm.reboot("recovery-update");
        }
    }

    private void processPackage(Context context, File file) throws Exception {
        if (!file.getCanonicalPath().startsWith("/data/")) {
            return;
        }
        Method method = android.os.RecoverySystem.class.getMethod("processPackage",
                Context.class, File.class, android.os.RecoverySystem.ProgressListener.class);

        method.invoke(null, context, file, null);
    }

    private void installPackageNextBoot(Context context, File file) throws Exception {
        Method method = android.os.RecoverySystem.class.getMethod("scheduleUpdateOnBoot",
                Context.class, File.class);

        method.invoke(null, context, file);
    }
}
